package org.jeecg.modules.flower.service.impl;/**
 * @author gf
 * @create 2022-9-22 9:33
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.flower.entity.FlowerCustom;
import org.jeecg.modules.flower.entity.FlowerOutorder;
import org.jeecg.modules.flower.entity.FlowerOutorderinfo;
import org.jeecg.modules.flower.entity.Xsgl;
import org.jeecg.modules.flower.mapper.FlowerOutorderMapper;
import org.jeecg.modules.flower.service.IFlowerCustomService;
import org.jeecg.modules.flower.service.XsglService;
import org.jeecg.modules.flower.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gf
 * @ClassName XsglServiceImpl
 * @description: TODO
 * @datetime 2022年 09月 22日 9:33
 * @version: 1.0
 **/
@Service
@Slf4j
public class XsglServiceImpl extends ServiceImpl<FlowerOutorderMapper, FlowerOutorder> implements XsglService {

    @Autowired
    private IFlowerCustomService flowerCustomService;

    @Value("${xsgl.baseurl}")
    private String baseurl;

    /**
     * 同步用户并增量插入到客户数据库
     *
     * @return java.lang.Integer
     * @descriptionauthor
     * @author gf
     * 2022-9-22 10:20
     * []
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer getXSGLUser() throws IOException {
        int pageNo = 1;
        int pageSize = 100;
        QueryWrapper<FlowerCustom> queryWrapper = new QueryWrapper<>();
        flowerCustomService.remove(queryWrapper);
        Integer xsglUsertwo = getXSGLUsertwo(pageNo, pageSize);
        return xsglUsertwo;
    }

    //循环插入数据库
    @Transactional(rollbackFor = Exception.class)
    public Integer getXSGLUsertwo(int pageNo, int pageSize) throws IOException {
        Integer rest = 0;
        String url = baseurl + "api/user/list?pageNo=" + pageNo + "&pageSize=" + pageSize;
        String token = getToken();
        JSONObject userJsonObject = CommonUtil.sendGet(url, token);
        if (userJsonObject != null) {
            boolean success = userJsonObject.getBoolean("success");
            Integer code = userJsonObject.getInteger("code");
            JSONObject result = userJsonObject.getJSONObject("result");

            if (success && code == 200) {
                Integer pages = result.getInteger("pages");
                Integer current = result.getInteger("current");
                JSONArray recordsList = result.getJSONArray("records");
                List<FlowerCustom> list = new ArrayList<>();
                for (int i = 0; i < recordsList.size(); i++) {
                    JSONObject dataInfo = (JSONObject) recordsList.get(i);
                    String address = dataInfo.getString("address");
                    String phone = dataInfo.getString("phone");
                    String name = dataInfo.getString("name");
                    String source = dataInfo.getString("source");
                    String id = dataInfo.getString("id");
                    String type = dataInfo.getString("type");
                    Integer type2 = 0;
                    if (StringUtils.isNotBlank(type)) {
                        if (!"个人".equals(type)) {// （0为个人，1为企业）
                            type2 = 1;
                        }
                    }
                    FlowerCustom flowerCustom = new FlowerCustom();
                    flowerCustom.setId(id);
                    flowerCustom.setName(name);
                    flowerCustom.setSource(source);
                    flowerCustom.setAddress(address);
                    flowerCustom.setPhone(phone);
                    flowerCustom.setCode(phone);
                    flowerCustom.setType(type2);
                    list.add(flowerCustom);
                    rest++;
                }
                flowerCustomService.saveBatch(list);
                if (current < pages) {
                    current++;
                    rest += getXSGLUsertwo(current, pageSize);
                }
            }
        }
        return rest;
    }

    /**
     * 获取用户余额
     *
     * @return java.math.BigDecimal
     * @descriptionauthor
     * @author gf
     * 2022-9-22 14:38
     * [userId]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BigDecimal getXSGLUserMoney(String userId) throws IOException {
        BigDecimal rest = BigDecimal.ZERO;
        String url = baseurl + "api/user/balance?userId=" + userId;
        String token = getToken();
        JSONObject userJsonObject = CommonUtil.sendGet(url, token);
        if (ObjectUtils.isNotEmpty(userJsonObject) && userJsonObject.size() > 0) {
            boolean success = userJsonObject.getBoolean("success");
            Integer code = userJsonObject.getInteger("code");
            BigDecimal result = userJsonObject.getBigDecimal("result");
            if (success && code == 200) {
                rest = result;
            }
        } else {
            throw new RuntimeException("获取余额失败");
        }
        return rest;
    }

    /**
     * 发送订单信息给销售系统
     *
     * @return java.lang.Integer
     * @descriptionauthor
     * @author gf
     * 2022-9-22 14:42
     * [userId, outAmount, outNo, outTime, settTime, settAmount, isInvoice, businessPersion]
     */
    @Override
    /*public Integer sendOrderInfo(String userId, BigDecimal outAmount, String outNo, Date outTime, Date settTime, BigDecimal settAmount, String isInvoice, String businessPersion,String outType) throws IOException {
        Integer rest = 0;
        String url = baseurl +  "api/order/outOrder" ;
//        String url =  "https://439v045v95.goho.co/jeecg-boot/api/order/outOrder" ;
        JSONObject param = new JSONObject();
        param.put("userId", userId);
        if(outAmount!=null){
            param.put("outAmount", outAmount);
        }
        param.put("outNo", outNo);
        param.put("outTime", outTime);
        if(settTime!=null) {
            param.put("settTime", settTime);
        }
        if(settAmount!=null) {
            param.put("settAmount", settAmount);
        }
        param.put("isInvoice", isInvoice);
        param.put("businessPersion", businessPersion);
        param.put("outType", outType);


        //推送订单信息给销售系统
        log.info("推送订单信息给销售系统userId:"+userId);
        log.info("推送订单信息给销售系统outAmount:"+outAmount);
        log.info("推送订单信息给销售系统outNo:"+outNo);
        log.info("推送订单信息给销售系统outTime:"+outTime);
        log.info("推送订单信息给销售系统settTime:"+settTime);
        log.info("推送订单信息给销售系统settAmount:"+settAmount);
        log.info("推送订单信息给销售系统isInvoice:"+isInvoice);
        log.info("推送订单信息给销售系统businessPersion:"+businessPersion);
        log.info("推送订单信息给销售系统outType:"+outType);
        log.info("推送tojson :  "+JSONObject.toJSONString( param ));


        JSONObject jsonResut = CommonUtil.sendPost(url, param, "");
        if (ObjectUtils.isNotEmpty(jsonResut) &&jsonResut.size() > 0) {
            if (!jsonResut.getBoolean("success")) {
                log.error("上传订单失败！"+ JSONObject.toJSONString(jsonResut));
                throw new RuntimeException("上传订单失败"+ JSONObject.toJSONString(jsonResut));
            }
            rest = 1;
        } else {
            throw new RuntimeException("推送订单信息给销售系统失败！");
        }
        return rest;
    }*/
    @Transactional(rollbackFor = Exception.class)
    public Integer sendOrderInfo(Xsgl xsgl) throws IOException {
        Integer rest = 0;
        String url = baseurl + "api/order/outOrder";
        JSONObject param = new JSONObject();
        param.put("userId", xsgl.getUserId());
        if (xsgl.getOutAmount() != null) {
            param.put("outAmount", xsgl.getOutAmount());
        }
        param.put("outNo", xsgl.getOutNo());
        param.put("outTime", xsgl.getOutTime());
        if (xsgl.getSettTime() != null) {
            param.put("settTime", xsgl.getSettTime());
        }
        if (xsgl.getSettAmount() != null) {
            param.put("settAmount", xsgl.getSettAmount());
        }
        param.put("isInvoice", xsgl.getIsInvoice());
        param.put("businessPersion", xsgl.getBusinessPersion());
        param.put("outType", xsgl.getOutType());
        if (xsgl.getSealNo() != null) {
            param.put("orderNo", xsgl.getSealNo());
        }


        //推送订单信息给销售系统
        log.info("推送订单信息给销售系统userId:" + xsgl.getUserId());
        log.info("推送订单信息给销售系统outAmount:" + xsgl.getOutAmount());
        log.info("推送订单信息给销售系统outNo:" + xsgl.getOutNo());
        log.info("推送订单信息给销售系统outTime:" + xsgl.getOutTime());
        log.info("推送订单信息给销售系统settTime:" + xsgl.getSettTime());
        log.info("推送订单信息给销售系统settAmount:" + xsgl.getSettAmount());
        log.info("推送订单信息给销售系统isInvoice:" + xsgl.getIsInvoice());
        log.info("推送订单信息给销售系统businessPersion:" + xsgl.getBusinessPersion());
        log.info("推送订单信息给销售系统outType:" + xsgl.getOutType());
        log.info("推送订单信息给销售系统orderNo:" + xsgl.getSealNo());
        log.info("推送tojson :  " + JSONObject.toJSONString(param));

        String token = getToken();
        JSONObject jsonResut = CommonUtil.sendPost(url, param, token);
        if (ObjectUtils.isNotEmpty(jsonResut) && jsonResut.size() > 0) {
            if (!jsonResut.getBoolean("success")) {
                log.error("上传订单失败！" + JSONObject.toJSONString(jsonResut));
                throw new RuntimeException("上传订单失败" + JSONObject.toJSONString(jsonResut));
            }
            rest = 1;
        } else {
            throw new RuntimeException("推送订单信息给销售系统失败！");
        }
        return rest;
    }


    /**
     * 订单确认出库（用于给客户发送提货码）
     *
     * @return void
     * @descriptionauthor
     * @author drt
     * 2022-11-15 11:13
     * [userId, outNo]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderConfirmOutStock(String userId, String outNo) {
        String url = baseurl + "api/order/confirmOut";
        JSONObject param = new JSONObject();
        param.put("userId", userId);
        param.put("outNo", outNo);
        log.info("调用订单确认出库接口（用于给客户发送提货码）userId:" + userId);
        log.info("调用订单确认出库接口（用于给客户发送提货码）outNo:" + outNo);
        try {
            String token = getToken();
            JSONObject jsonResult = CommonUtil.sendPost(url, param, token);
            if (ObjectUtils.isNotEmpty(jsonResult) && jsonResult != null && jsonResult.size() > 0) {
                if (!jsonResult.getBoolean("success")) {
                    log.error("调用订单确认出库接口（用于给客户发送提货码）失败！" + JSONObject.toJSONString(jsonResult));
                    //throw new RuntimeException("调用订单确认出库接口（用于给客户发送提货码）失败"+ JSONObject.toJSONString(jsonResult));
                } else {
                    log.error("调用订单确认出库接口（用于给客户发送提货码）失败！" + JSONObject.toJSONString(jsonResult));
                }
            } else {
                log.error("调用订单确认出库接口（用于给客户发送提货码）失败！" + JSONObject.toJSONString(jsonResult));
                //throw new RuntimeException("调用订单确认出库接口（用于给客户发送提货码）！");
            }
        } catch (Exception e) {
            log.error("调用订单确认出库接口（用于给客户发送提货码）失败！" + e.getMessage());
        }
    }


    /**
     * 取消订单(给用户退款)
     *
     * @return void
     * @descriptionauthor
     * @author drt
     * 2022-12-02 10:40
     * sealNo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(String sealNo) throws IOException {
        String url = baseurl + "api/order/refund";
        JSONObject param = new JSONObject();
        param.put("sealNo", sealNo);
        log.info("推送取消订单信息给销售系统sealNo:" + sealNo);
        String token = getToken();
        JSONObject jsonResult = CommonUtil.sendPost(url, param, token);
        if (ObjectUtils.isNotEmpty(jsonResult) && jsonResult.size() > 0) {
            if (!jsonResult.getBoolean("success")) {
                log.error("推送取消订单到销售系统失败！" + JSONObject.toJSONString(jsonResult));
                throw new RuntimeException("推送取消订单到销售系统失败！" + JSONObject.toJSONString(jsonResult));
            }
        } else {
            throw new RuntimeException("推送取消订单到销售系统失败！");
        }
    }

    /**
     * 获取token
     *
     * @return void
     * @author drt
     * 2023-01-06 16:00
     */
    @Override
    public String getToken() {
        String url = baseurl + "sys/screenLogin";
        JSONObject param = new JSONObject();
        param.put("username", "hjp-ch");
        param.put("password", "1qaz@WSX");
        log.info("从销售系统获取token");
        String token = "";
        JSONObject jsonResult = CommonUtil.sendPost(url, param, "");
        if (ObjectUtils.isNotEmpty(jsonResult) && jsonResult.size() > 0) {
            if (jsonResult.getBoolean("success")) {
                String result = jsonResult.getString("result");
                JSONObject jsonObject = JSON.parseObject(result);
                token = jsonObject.getString("token");
            } else {
                throw new RuntimeException("从销售系统获取token失败！");
            }
        } else {
            throw new RuntimeException("从销售系统获取token失败！");
        }
        return token;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void senOutNotice(String sealNo) throws IOException {
//        api/order/modifyState'+ '?orderId=' + this.outOrder.sealNo
        String url = baseurl + "api/order/modifyState?orderId=" + sealNo;
        JSONObject param = new JSONObject();
//        param.put("sealNo", sealNo);
        log.info("推送 出库确认成功通知 给销售系统sealNo:" + sealNo);
        String token = getToken();
        JSONObject jsonResult = CommonUtil.sendGet(url, token);
        if (ObjectUtils.isNotEmpty(jsonResult) && jsonResult.size() > 0) {
            if (!jsonResult.getBoolean("success")) {
                log.error("推送 出库成功通知 给销售系统sealNo 失败！" + sealNo + JSONObject.toJSONString(jsonResult));
//                throw new RuntimeException("推送 出库成功通知 给销售系统sealNo失败！"+sealNo+ JSONObject.toJSONString(jsonResult));
            }
        } else {
            log.error("推送 出库成功通知 给销售系统sealNo 失败！" + sealNo + JSONObject.toJSONString(jsonResult));
//            throw new RuntimeException("推送 出库成功通知 给销售系统sealNo失败！"+sealNo);
        }
    }

    /**
     * 发送实际出库数量给销售系统。
     *
     * @return void
     * @descriptionauthor
     * @author gf
     * 2023-3-1 14:50
     * [orderNum销售系统单号, outNo出库单号, outers出库人, flowerOutorderinfo]
     * [success  如果为true 则修改订单为已发货  否则返还客户余额 订单失效
     * message   stirng   // succes为fasle时原因
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void senOutOrderTnumbers(String orderNum, String outNo, String outers, boolean success, String message, List<FlowerOutorderinfo> flowerOutorderinfoList) {
        String url = baseurl + "/api/order/delivery";
        JSONObject param = new JSONObject();
        ArrayList<JSONObject> details = new ArrayList<>();
        for (FlowerOutorderinfo flowerOutorderinfo : flowerOutorderinfoList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", flowerOutorderinfo.getId());
            jsonObject.put("actualAmount", flowerOutorderinfo.getNumber());
            details.add(jsonObject);
        }

        param.put("orderNum", orderNum);
        param.put("outNo", outNo);
        param.put("outers", outers);
        param.put("details", details);
        param.put("success", success);
        param.put("message", message);
        log.info("推送 出库出库实际库存 给销售系统sealNo: " + orderNum + "--CK:" + outNo);
        String token = getToken();
        JSONObject jsonResult = CommonUtil.sendPost(url, param, token);
        if (ObjectUtils.isNotEmpty(jsonResult) && jsonResult.size() > 0) {
            if (!jsonResult.getBoolean("success")) {
                log.error("推送 出库出库实际库存 给销售系统sealNo 失败！" + orderNum + "--CK:" + outNo + JSONObject.toJSONString(jsonResult));
                log.error("推送 出库出库实际库存 给销售系统sealNo 失败！" +  JSONObject.toJSONString(param));
//                throw new RuntimeException("推送 出库成功通知 给销售系统sealNo失败！"+sealNo+ JSONObject.toJSONString(jsonResult));
            }
        } else {
            log.error("推送 出库出库实际库存  给销售系统sealNo 失败！" + orderNum + "--CK:" + outNo + JSONObject.toJSONString(jsonResult));
            log.error("推送 出库出库实际库存 给销售系统sealNo 失败！" +  JSONObject.toJSONString(param));
//            throw new RuntimeException("推送 出库成功通知 给销售系统sealNo失败！"+sealNo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sureOutBack(String orderNum) throws IOException {
        String url = baseurl + "/api/order/delivery/cancel?orderNum="+orderNum;

        log.info("  撤销确认出库 给销售系统sealNo: " + orderNum);
        String token = getToken();
        JSONObject jsonResult = CommonUtil.sendGet(url,  token);
        if (ObjectUtils.isNotEmpty(jsonResult) && jsonResult.size() > 0) {
            if (!jsonResult.getBoolean("success")) {
                log.error("  撤销确认出库11 给销售系统sealNo 失败！" + orderNum + "====" + JSONObject.toJSONString(jsonResult));
                throw new RuntimeException("撤销确认出库 给销售系统sealNo 失败！" + orderNum + "====" + JSONObject.toJSONString(jsonResult));
            }
        } else {
            log.error("撤销确认出库22  给销售系统sealNo 失败！" + orderNum + "====" + JSONObject.toJSONString(jsonResult));
            throw new RuntimeException("撤销确认出库 给销售系统sealNo 失败！" + orderNum + "====" + JSONObject.toJSONString(jsonResult));
        }
    }
}
